package org.bronycorps.mlptss.domain.controller;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

import org.bronycorps.mlptss.MlpTss;
import org.bronycorps.mlptss.domain.model.SpecialBullet;
import org.bronycorps.mlptss.domain.model.script.SpecialAttackScriptMediator;
import org.bronycorps.mlptss.manager.scripting.ScriptManager;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Vector2;

public class SpecialBulletController extends AbstractController {

	private Invocable invocableScript;
	private float lifespan;
	private SpecialBullet model;
	private ScriptEngine script;
	private SpecialAttackScriptMediator scriptMediator;

	public SpecialBulletController(SpecialBullet model) {
		super();
		this.model = model;
		this.lifespan = model.getDuration();

		this.script = ScriptManager.getInstance().getScript(
				model.getScriptName() + ".js");
		this.invocableScript = (Invocable) this.script;

		this.scriptMediator = new SpecialAttackScriptMediator(model);
	}

	@Override
	public void act(float delta) {
		this.lifespan -= delta;

		try {
			this.model.setPosition((Vector2) this.invocableScript
					.invokeFunction("updateSpecialAttackPosition", delta,
							this.model.getPosition(), this.scriptMediator));
		} catch (NoSuchMethodException e) {
			Gdx.app.error(MlpTss.LOG, "Special attack Script not found", e);
		} catch (ScriptException e) {
			Gdx.app.error(MlpTss.LOG, "Special attack Script error", e);
		}

	}

	public float getLifespan() {
		return this.lifespan;
	}

	public SpecialBullet getModel() {
		return this.model;
	}
}
